package com.freshmarket.freshmarket.controller;


import com.freshmarket.freshmarket.configuration.Constant;
import com.freshmarket.freshmarket.controller.form.InsertProductForm;
import com.freshmarket.freshmarket.controller.form.SelectProductForm;
import com.freshmarket.freshmarket.controller.result.BackProductResult;
import com.freshmarket.freshmarket.service.impl.ProductServiceImpl;
import com.freshmarket.freshmarket.utils.Result;
import com.freshmarket.freshmarket.utils.Utils;
import com.squirrel.cos.COSAPI;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Squirrel
 * @since 2020-09-04
 */
@RestController
@RequestMapping("/freshmarket/product")
public class ProductController {

    final COSAPI cosapi;
    final ProductServiceImpl productService;

    public ProductController(COSAPI cosapi, ProductServiceImpl productService) {
        this.cosapi = cosapi;
        this.productService = productService;
    }

    /**
     * @author Squbi
     * @date 2020/9/6 15:35
     * @Description 上传图片
     */
    @RequestMapping("/uploadImg")
    public Result uploadImg(MultipartFile file)throws Exception{
        String originalFilename = Utils.getTime()+file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        cosapi.uploadByStream(originalFilename,inputStream,null,file.getSize());
        return Result.successResult(Constant.CosUrl +originalFilename);
    }

    /**
     * @author Squbi
     * @date 2020/9/6 15:35
     * @Description 删除上传的图片
     */
    @RequestMapping("/deleteImg")
    public Result deleteImg(String url)throws Exception{
        cosapi.deleteObject(url.replace(Constant.CosUrl,""));
        return Result.successResult();
    }

    @RequestMapping("/insertProduct")
    public Result insertProduct(@Valid InsertProductForm insertProductForm)throws Exception{
        productService.insertProduct(insertProductForm);
        return Result.successResult();
    }

    @RequestMapping("/selectProduct")
    public Result selectProduct(SelectProductForm selectProductForm)throws Exception{
        List<BackProductResult> backProductResults = productService.selectProduct(selectProductForm);
        return Result.successResult(backProductResults);
    }
}

